package com.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Date: 2024/6/18 21:22
 * Author: T_log
 * Description: PathCacheDemo
 */
public class PathCacheDemo {


    //节点数据改变可参考/pic/pathcache.png
    public static void main(String[] args) throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", retryPolicy);


        client.start();
        System.out.println("已经成功的连接ZK服务了....");


        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/path", true);

        //pathCache就是把zk里面的数据缓存到我们的客户端里面来
        //我们可以对这个缓存数据加监听，从而达到观察ZK数据变化的目的
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                System.out.println("收到zk服务端的数据变化通知了......" + pathChildrenCacheEvent);
            }
        });

        pathChildrenCache.start();

        Thread.sleep(Integer.MAX_VALUE);
    }
}
